document.addEventListener('DOMContentLoaded', function() {
    // 获取页面元素
    const targetLanguage = document.getElementById('target-language');
    const translationApi = document.getElementById('translation-api');
    const translatePage = document.getElementById('translate-page');
    const translateSelection = document.getElementById('translate-selection');

    // 从存储中加载设置
    chrome.storage.sync.get(['targetLanguage', 'translationApi'], function(result) {
        if (result.targetLanguage) {
            targetLanguage.value = result.targetLanguage;
        }
        if (result.translationApi) {
            translationApi.value = result.translationApi;
        }
    });

    // 保存设置
    function saveSettings() {
        chrome.storage.sync.set({
            targetLanguage: targetLanguage.value,
            translationApi: translationApi.value
        });
    }

    // 监听设置变化
    targetLanguage.addEventListener('change', saveSettings);
    translationApi.addEventListener('change', saveSettings);

    // 翻译整个页面
    translatePage.addEventListener('click', function() {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            chrome.tabs.sendMessage(tabs[0].id, {
                action: 'translatePage',
                targetLanguage: targetLanguage.value,
                translationApi: translationApi.value
            });
        });
    });

    // 划词翻译
    translateSelection.addEventListener('click', function() {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            chrome.tabs.sendMessage(tabs[0].id, {
                action: 'toggleSelection',
                targetLanguage: targetLanguage.value,
                translationApi: translationApi.value
            });
        });
    });
});
